import axios from "axios";

// 创建axios实例
const http = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    return config;
  },
  (e) => Promise.reject(e),
);

//添加返回值类型，支持泛型
interface Data<T> {
  code: number;
  msg: string;
  data: T;
}

// axios响应式拦截器
http.interceptors.response.use(
  <T>(res: axios.AxiosResponse): T => {
    // 确保状态码有效
    if (res.status >= 200 && res.status < 300) {
      return Promise.resolve(res.data as Data<T>);
    }
    return Promise.reject(new Error("Response status not OK"));
  },
  (e) => {
    //响应错误

    return Promise.reject(e);
  },
);

export default http;
